package edu.jamestang.yeb.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import edu.jamestang.yeb.entity.*;
import edu.jamestang.yeb.service.*;
import edu.jamestang.yeb.util.PageResp;
import edu.jamestang.yeb.util.Resp;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * @author JamesTang
 * @date 2021/12/22 11:24
 */

@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PoliticsStatusService politicsStatusService;

    @Autowired
    private NationService nationService;

    @Autowired
    private JobLevelService jobLevelService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PositionService positionService;

    @ApiOperation(value = "Get all Employee(Page)")
    @GetMapping("/")
    public PageResp getAllEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                   @RequestParam(defaultValue = "10") Integer size,
                                   Employee employee, LocalDate[] dateScope){
        return employeeService.getEmployeeByPage(currentPage,size,employee,dateScope);
    }

    @ApiOperation(value = "Get all politicsStatus")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> getAllPoliticsStatus() {
        return politicsStatusService.list();
    }

    @ApiOperation(value = "Get all jobLevels")
    @GetMapping("/joblevels")
    public List<JobLevel> getAllJobLevels() {
        return jobLevelService.list();
    }

    @ApiOperation(value = "Get all nations")
    @GetMapping("/nations")
    public List<Nation> getAllNations() {
        return nationService.list();
    }

    @ApiOperation(value = "Get all positions")
    @GetMapping("/Positions")
    public List<Position> getAllPositions() {
        return positionService.list();
    }

    @ApiOperation(value = "Get all department")
    @GetMapping("/deps")
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartments();
    }

    @ApiOperation(value = "Get ID")
    @GetMapping("/maxWorkID")
    public Resp getWorkId(){
        return employeeService.maxWorkId();
    }

    @ApiOperation(value = "Add Employee")
    @PostMapping("/")
    public Resp addEmployee(@RequestBody Employee employee){
        return employeeService.addEmployee(employee);
    }

    @ApiOperation(value = "Update Employee")
    @PutMapping("/")
    public Resp updateEmployee(@RequestBody Employee employee){
        if(employeeService.updateById(employee)){
            return Resp.success("Update successful");
        }
        return Resp.error("Update fail");
    }

    @ApiOperation(value = "Delete Employee")
    @DeleteMapping("/{id}")
    public Resp deleteEmployee(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return Resp.success("Delete successful");
        }
        return Resp.error("Delete fail");
    }

    @ApiOperation(value = "Export excel file")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportExcel(HttpServletResponse response){

        List<Employee> list = employeeService.getEmployee(null);
        ExportParams params = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class,list);
        ServletOutputStream outputStream = null;
        try{
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null != outputStream){
                try {
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "Import excel file")
    @PostMapping("/import")
    public Resp importExcel(MultipartFile excelFile){

        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<JobLevel> jobLevelList = jobLevelService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(excelFile.getInputStream(), Employee.class, importParams);
            list.forEach(employee -> {

                Nation nation = nationList.get(nationList.indexOf(new Nation(employee.getNation().getName())));
                employee.setNationId(nation.getId());

                PoliticsStatus politicsStatus = politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName())));
                employee.setPoliticId(politicsStatus.getId());

                Department department = departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName())));
                employee.setDepartmentId(department.getId());

                JobLevel jobLevel = jobLevelList.get(jobLevelList.indexOf(new JobLevel(employee.getJoblevel().getName())));
                employee.setJobLevelId(jobLevel.getId());

                Position position = positionList.get(positionList.indexOf(new Position(employee.getPosition().getName())));
                employee.setPosId(position.getId());

            });

            if(employeeService.saveBatch(list)){
                return Resp.success("Import successful");
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

        return Resp.error("Import fail");
    }
}
